#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

const inquirer = require("inquirer");
const ejs = require('ejs');

function copyTemplateFiles(dir, answers) {
    fs.readdir(dir, (error, files) => {
        if (error) {
            console.log(`Failed to read template files because ${error}`);
            return;
        }

        files.forEach(file => fs.stat(path.join(dir, file), (error, stats) => {
            if (error) {
                console.log(`Failed to read template file because ${error}`);
                return;
            }

            let templatePath = path.join(__dirname, 'templates');
            let srcPath = path.join(dir, file);
            let dstPath = path.join(process.cwd(), srcPath.replace(templatePath, ''));

            if (stats.isFile()) {
                ejs.renderFile(srcPath, answers, (error, result) => {
                    if (error) {
                        console.log(`Failed to create template files because ${error}`);
                        return;
                    }

                    let dir = dstPath.substring(0, dstPath.lastIndexOf('\\'));
                    fs.mkdir(dir, {recursive: true}, (error) => {
                        fs.writeFile(dstPath, result, error => {
                            if (!error) {
                                return;
                            }
    
                            console.log(`Failed to copy template files because ${error}`);
                        });
                    });
                })
                return;
            }

            copyTemplateFiles(path.join(dir, file), answers);
        }));
    });
}

inquirer.prompt([
    {
        type: 'input',
        name: 'projectName',
        message: 'Project Name is: '
    }
]).then(answers => {
    copyTemplateFiles(path.join(__dirname, 'templates'), answers);
})